package encoder

import (
	"time"

	"github.com/pion/rtp"
	"github.com/pion/rtp/codecs"
	"gogs.smarteye.com/servere/gobvrtp/encoder/packetizer"
)

type RtpEncoder struct {
	// payload type of packets.
	PayloadType uint8

	// SSRC of packets (optional).
	// It defaults to a random value.
	SSRC *uint32

	// initial sequence number of packets (optional).
	// It defaults to a random value.
	InitialSequenceNumber *uint16

	// maximum size of packet payloads (optional).
	// It defaults to 1460.
	PayloadMaxSize int

	SampleRate int

	sequenceNumber uint16

	packetizer rtp.Packetizer
}

// Init initializes the encoder.
func (e *RtpEncoder) Init() error {
	if e.SSRC == nil {
		v, err := randUint32()
		if err != nil {
			return err
		}
		e.SSRC = &v
	}
	if e.InitialSequenceNumber == nil {
		v, err := randUint32()
		if err != nil {
			return err
		}
		v2 := uint16(v)
		e.InitialSequenceNumber = &v2
	}
	if e.PayloadMaxSize == 0 {
		e.PayloadMaxSize = defaultPayloadMaxSize
	}

	e.sequenceNumber = *e.InitialSequenceNumber

	e.packetizer = rtp.NewPacketizer(uint16(e.PayloadMaxSize), e.PayloadType, *e.SSRC,
		&packetizer.RTPPayLoader{},
		packetizer.NewFixedSequencer(e.sequenceNumber),
		uint32(e.SampleRate),
	)

	return nil
}

// Encode encodes an audio frame into a RTP packet.
func (e *RtpEncoder) Encode(frame []byte, samples time.Duration) ([]*rtp.Packet, error) {
	packets := e.packetizer.Packetize(frame, uint32(samples.Milliseconds()))
	return packets, nil
}

func test() {
	p := rtp.NewPacketizer(defaultPayloadMaxSize, 98, 12345,
		&packetizer.RTPPayLoader{},
		packetizer.NewFixedSequencer(0),
		90000,
	)
	p.Packetize(nil, 0)

	rtp.NewPacketizer(defaultPayloadMaxSize, 96, 1122,
		&codecs.H264Payloader{},
		rtp.NewFixedSequencer(85),
		8000,
	)

	_ = codecs.OpusPayloader{}
}
